package JUC_Advanced.chapter1_CompletableFuture.api;

import JUC_Advanced.ThreadPool;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Author: GuSongLiao
 * @Date: 2024/3/7 10:53
 * @Description: api deno
 */

/**
 * thenCombine 合并两个结果进行第三步的运算
 */
public class CompletableFutureApi_thenCombine {

    public static void main(String[] args) {

        /**
         * 需求如下，两个玩家 PK，谁速度快选谁
         */
        CompletableFuture<Integer> playA = CompletableFuture.supplyAsync(() -> {
            System.out.println("player A come in -------");
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
            return 10;
        }, ThreadPool.THREAD_POOL);

        CompletableFuture<Integer> playB = CompletableFuture.supplyAsync(() -> {
            System.out.println("player B come in -------");
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            return 20;
        }, ThreadPool.THREAD_POOL);

        // 重要API
        CompletableFuture<Integer> result = playA.thenCombine(playB, (a, b) -> {
            System.out.println("a = " + a);
            System.out.println("b = " + b);
            return a + b;
        });

        System.out.println(result.join());

        System.out.println("主线程忙别的去了");
    }
}
